import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
import { CanvasMode, EventItemType, RunState } from './dict';
import WorkFlowGraph from './graph-wrapper/work-flow-graph';
import styles from './WorkFlowEditor.less';

// 仅合并node的运行状态，线的运行状态还未合并
function mergeNodeRunState(flowGraphData) {
  const { highLightedNodes, highLightedFlows, currentNode, bpmnJson } = flowGraphData;
  const cellsObj = JSON.parse(bpmnJson);
  cellsObj.cells.forEach((cell) => {
    const type = cell?.data.type || EventItemType.Edge;
    if (type === EventItemType.Edge) return;
    if (highLightedNodes.indexOf(cell.id) !== -1) cell.data.runstate = RunState.Pass;
    else if (currentNode && currentNode === cell.id) cell.data.runstate = RunState.Run;
    else cell.data.runstate = RunState.Wait;
  });
  return cellsObj;
}

function ViewCanvas(props, ref) {
  // flowRunData 格式：
  // data: {
  //   highLightedNodes: [],  // 需要高亮的 react node 的 id 数组
  //   highLightedFlows: [],  // 需要高亮的 edge 的 id 数组
  //   currentNode: id,   // 当前运行节点的id
  //   bpmnJson: String  // 需要 JSON.parse
  // }
  //
  // bpmnJson JSON.parse之后的字段结构:
  // {  // 这个结构就是x6绘图canvas到处的结构
  //   "cells": []
  // }
  const { flowRunData, dispatch, ...restProps } = props;

  const containerRef = useRef(null);
  const canvasRef = useRef(null);
  const flowGraphRef = useRef(null);

  useImperativeHandle(ref, () => ({
    flowGraphRef,
  }));

  // 渲染画布
  useEffect(() => {
    if (flowRunData) {
      flowGraphRef.current = new WorkFlowGraph(CanvasMode.Run);
      flowGraphRef.current.workflowGraph$.next(mergeNodeRunState(flowRunData));
      flowGraphRef.current.renderGraph(containerRef.current, canvasRef.current, dispatch);
      flowGraphRef.current.updageEdgeRunState(flowRunData.highLightedFlows);
    }
    return () => {
      if (flowGraphRef.current) {
        flowGraphRef.current.dispose();
        flowGraphRef.current = null;
      }
    };
  }, [flowRunData, dispatch]);

  return (
    <div
      ref={(elem) => {
        containerRef.current = elem;
      }}
      className={styles.dropWapper}
      {...restProps}
    >
      <div style={{ height: '100%', width: '100%' }} ref={canvasRef} />
    </div>
  );
}

export default forwardRef(ViewCanvas);
